from models import ActionCategory, NextAction, Project, Task, ConfigSetting, SomedayMaybeIdea
from google.appengine.api import users

import logging

config_map = {
  'mru_email': 'Most recently used destination email',
  'mru_cat_email': 'Most recently used category for email report'}

def cuser():
  return users.get_current_user()
  
def actions():
  return NextAction.gql("where user=:user and is_complete=:complete order by has_due_date,due_date", user=cuser(), complete=False)
  
def completed_actions():
  return NextAction.gql("where user=:user and is_complete=:complete order by complete_date desc", user=cuser(), complete=True)

def categories():
  return ActionCategory.gql("where user=:user order by name", user=cuser())
  
def someday_maybe_ideas():
  return SomedayMaybeIdea.gql("where user=:user order by name", user=cuser())

def projects():
  return Project.gql("where user=:user and is_complete=:complete order by description", user=cuser(), complete=False)

def completed_projects():
  return Project.gql("where user=:user and is_complete=:complete order by description", user=cuser(), complete=True)

def open_tasks():
  tasks = Task.gql("where user=:user and is_complete=:complete order by parent_project,due_date", user=cuser(), complete=False)
  return set.union(set(tasks), set(actions()))
  
def actions_by_category(cat_name):
  category = ActionCategory.gql("where user=:user and name=:name", user=cuser(), name=cat_name).get()
  return NextAction.gql("where user=:user and is_complete=:complete and category=:cat", user=cuser(), complete=False, cat=category)
  
def get_config_setting(config_key):
  return ConfigSetting.gql("where user=:user and setting_key=:key limit 1", user=cuser(), key=config_key).get()
  
def get_config_value(config_key):
  return get_config_setting(config_key).value
  
def set_config(key, value):
  mru = get_config_setting(key)
  if not mru:
    mru = ConfigSetting()
    mru.setting_key = key
  mru.value = value
  mru.description = config_map[key]
  mru.user = cuser()
  mru.put()
  
def settings():
  return ConfigSetting.gql("where user=:user", user=cuser())

